package com.xmb.wcapi.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xmb.wcapi.constant.R;
import com.xmb.wcapi.entity.StockNow;
import com.xmb.wcapi.service.IStockNowService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * <p>
 * 现存量记录表 前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-07-24
 */
@RestController
@RequestMapping("/stock-now")
public class StockNowController {

    @Autowired
    private IStockNowService iStockNowService;

    @RequestMapping("/upload")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R upload(String data) {
        if (StringUtils.isEmpty(data)) {
            return R.error("未读取到数据");
        }
        // 去除第一列表头
        JSONArray objects = JSONUtil.parseArray(data);
        objects.remove(0);

        List<StockNow> list = JSONUtil.toList(objects, StockNow.class);
        // 数据去重
        Map<String, Long> collect = new ArrayList<>(list.stream()
                .collect(Collectors.toMap(
                        p -> Collections.singletonList(p.getMaterial()), // 为多属性创建键
                        p -> p, // 原对象为值
                        (existing, replacement) -> existing // 冲突时保留现有对象
                ))
                .values())
                .stream()
                .collect(Collectors.toMap(StockNow::getMaterial, StockNow::getMaterialSum));

        // 查询已有数据
        List<StockNow> stockNows = iStockNowService.list(Wrappers.lambdaQuery(StockNow.class).in(StockNow::getMaterial, collect.keySet()));
        if (stockNows.isEmpty()){
            return R.error("导入失败！未查询到料号数据！");
        }

        // 变更值
        for (StockNow now : stockNows) {
            now.setMaterialSum(collect.get(now.getMaterial()));
        }

        // 更新值
        iStockNowService.updateBatchById(stockNows);

        return R.ok();
    }

}

